const conf = {
  data: {
    // hasEmptyGrid 变量控制是否渲染空格子，若当月第一天是星期天，就不应该渲染空格子
    hasEmptyGrid: false ,
    haslast:false,
    tourist_num:{
      adult:0,
      children:0,
      sum:0,
      flag:true
    },
    url:"https://app1.sztravel.com.cn/file/weixinapp/img/",
    a_day:[],//当月可选团期
    select_day:[],//当月可选日期控制开关
    thisday:[],
    date:'',
    enableDay:[],
    selectInfo:{},
    total_price:0.00
  },
  navto_order(){
    if(this.data.tourist_num.sum>0){
      let test_info={}
      test_info.date = this.data.selectInfo.time_day;
      test_info.adult_price = this.data.selectInfo.adult_price;
      test_info.child_price = this.data.selectInfo.child_price;
      test_info.adult_num = this.data.tourist_num.adult;
      test_info.child_num = this.data.tourist_num.children;
      test_info.total_price = this.data.total_price;
      test_info.total_num = this.data.tourist_num.sum;
      test_info.teem_id = this.data.selectInfo.team_id;
      try {
        wx.setStorageSync('test_info', JSON.stringify(test_info))
      } catch (e) {
      };
      wx.redirectTo({
        url: '../../pages/cost_detail/cost_detail',
        success: function (res) {
          // success
        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        }
      })
    }else{
      wx.showToast({
        title: '请选择日期和人数',
        icon: '',
        image:'../../img/time.png',
        duration: 2000
      })
    }
  },
  //控制选中状态和选中日期
  select_this(e){ 
    let index = e.target.dataset.i;
    // let this_day =false
      // this.data.thisday[index]
    let thisday = [];
    let info=e.target.dataset.info;
    thisday[index] =true;
    
    if(thisday[index]){
      thisday["select"] = index;
    } 
    this.setData({
      thisday: thisday,
      selectInfo:info
    })
    // console.log(this.data)
  },
  //控制选择的人数、以及分类
  touristchange(e){
    var cdata = this.data.tourist_num; 
    let child_price = parseFloat(this.data.selectInfo.child_price);
    let adult_price = parseFloat(this.data.selectInfo.adult_price);
    let total_price; 
    
    if (this.data.selectInfo.stock==0){
      return;
    }
     if(e.target.dataset.adult){
      //成人
      if(e.target.dataset.adult==2){
          cdata.adult--
          if(cdata.adult<0){
            cdata.adult=0
          }else{
            cdata.sum--
          }
        }else{
          if(cdata.flag){
            cdata.adult++
            cdata.sum++
          }
        }
    }else if(e.target.dataset.children){
      //儿童
        if(e.target.dataset.children==2){
          cdata.children--
          if(cdata.children<0){
            cdata.children=0
          }else{
            cdata.sum--
          } 
        }else{
          if(cdata.flag){
            cdata.children++
            cdata.sum++
          }
          
        }
    };
     if (cdata.sum >= this.data.selectInfo.stock) {
       cdata.flag=false;
     }else{
       cdata.flag = true;
     };
     total_price = (child_price * cdata.children + adult_price * cdata.adult).toFixed(2)
    //  console.log(total_price)
    this.setData({
      tourist_num:cdata,
      total_price: total_price
    })
    
  },
  getSystemInfo() {
    try {
      const res = wx.getSystemInfoSync();
      this.setData({
        scrollViewHeight: res.windowHeight * res.pixelRatio || 667
      });
    } catch (e) {
      console.log(e);
    }
  },
  //小日历开始                                                、、小日历开始
  // 获取当月共多少天
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  // 获取当月第一天星期几
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  getLastDayOfWeek(year, month){
    var days = this.getThisMonthDays(year, month);
    // console.log(days)
    return new Date(Date.UTC(year, month - 1, days)).getDay();
  },
  // 计算当月1号前空了几个格子
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  //计算当月最后一天空的格子数量
  computelast(year, month){
    var lastday = this.getLastDayOfWeek(year, month);
    var last = [];
    if(lastday!=6){
      for(let i=0;i<6-lastday;i++){
        last.push(i);
      }
      this.setData({
        haslast:true,
        last:last
      })
    }else{
      this.setData({
         haslast:false,
          last:[]
      })
    }
  },
  // 绘制当月天数占的格子
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);//当月天数
    //渲染可以选择的日期
    let select_day =[];
    let a_day = this.data.a_day;
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push(i);
      for(let j=0;j<a_day.length;j++){
        if (i == parseInt(a_day[j].time_day.substring(8, 11))){
          select_day[i] = { flag: true, data: a_day[j]}
          break
        }else{
          select_day[i] = { flag: false, data:null}
        }
      }
    }
    //结束  渲染可以选择的日期
    this.setData({
      days,
      select_day
    });
    
  },
  // 初始化数据
  onLoad(options){
    var enableDay, startday, a_day = [], selectInfo={};
    try {
       enableDay = JSON.parse(wx.getStorageSync('enable_team_list'));
    } catch (e) {
    }
    if(options.startday){
       startday = options.startday;
    }else{
      startday = enableDay[0].time_day;
    }
    for(let k=0;k<enableDay.length;k++){//放置进来时日期
      if (enableDay[k].time_day.substring(0, 7) == startday.substring(0, 7)){//进入年份和月份
        a_day.push(enableDay[k])
        // parseInt(enableDay[k].time_day.substring(8, 11))
      }
      if (enableDay[k].time_day === startday){//选中初始（默认）日期
        selectInfo = enableDay[k]
      }
    }
    let intday = parseInt(options.startday.substring(8))//初始日期
    let thisday=[];
    thisday[intday]=true;
    thisday["select"] = intday;
    // console.log(a_day)
    // console.log(startday)
    // console.log(enableDay)
    const date = new Date();
    const cur_year = startday.substring(0, 4)
    const cur_month = startday.substring(5,7)
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.setData({
      cur_year,
      cur_month,
      weeks_ch,
      a_day: a_day,
      enableDay:enableDay,
      selectInfo: selectInfo,
      thisday:thisday
    })
    this.calculateEmptyGrids(cur_year, cur_month);
    this.computelast(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.getSystemInfo();
    
    console.log(this.data)
  },
  onShow:function(){
    wx.removeStorageSync("check_info")
  },
  // 切换控制年月
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = parseInt(this.data.cur_year);
    const cur_month = parseInt(this.data.cur_month);
    var enableDay=this.data.enableDay;    
    if (handle === 'prev') {
      let a_day = []
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }
      for(let i=0;i<enableDay.length;i++){
        let en_year = parseInt(enableDay[i].time_day.substring(0, 4));
        let en_mouse = parseInt(enableDay[i].time_day.substring(5, 7));
        if (en_year == newYear && en_mouse == newMonth){
          a_day.push(enableDay[i])
        }
      }
      // console.log(555)
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        a_day: a_day,
        thisday:[]
      })
      // console.log(this.data)
      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      this.computelast(newYear, newMonth);
      
      
    } else {
      let a_day = []
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }
     
      for(let i = 0; i < enableDay.length; i++) {
        let en_year = parseInt(enableDay[i].time_day.substring(0, 4));
        let en_mouse = parseInt(enableDay[i].time_day.substring(5,7));
        if (en_year == newYear && en_mouse == newMonth) {
          a_day.push(enableDay[i])
        }
      }
      // console.log(555)
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        a_day: a_day,
        thisday: []
      })
    //  console.log(this.data)
      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      this.computelast(newYear, newMonth);
      
    }
   
  },
  //日历结束  、、、             结束
  
};

Page(conf);